<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/6
 * Time: 13:06
 */

namespace App\Http\Controllers\Backstage;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Validator\AdminVail;
use App\Model\Account\Type;
use App\Model\Backstage\Customers;
use App\Model\Backstage\User;
use App\Tool\Error;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;

class CustomersController extends Controller
{
    /** 客源列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function listCustomers(Request $request,Customers $customers, User $user)
    {
        $parameter = $request->all();
        $where = [];

        $where[] = ['c_status', '=', 1];//过滤非回收站房源
        //获取公司的ID
//        $branchId = 2;
//        $where[] = ['c_branch_id', '=', $branchId];
        //二级区域ID
        if ($request->input('c_area_id')){
            $where[] = ['c_area_id', 'like', '%'.$parameter['c_area_id'].'%'];
        }
        //三级区域ID
        if ($request->input('c_secondary_area')){
            $where[] = ['c_secondary_area', 'like', '%'.$parameter['c_secondary_area'].'%'];
        }
        //房型
        if ($request->input('c_room')){
            $where[] = ['c_room', '=', $parameter['c_room']];
        }
        //交易类型
        if ($request->input('c_trading_type')){
            $where[] = ['c_trading_type', '=', $parameter['c_trading_type']];
        }
        //客源状态
        if ($request->input('c_buy_status')){
            $where[] = ['c_buy_status', '=', $parameter['c_buy_status']];
        }
        //用途
        if ($request->input('c_use_type')){
            $where[] = ['c_use_type', '=', $parameter['c_use_type']];
        }
        //日期 1：委托日期   2：最后跟进日期   3：首次录入时间  前台直接传时间戳

        //委托时间
        if ($request->input('date_type') == 1){
            if ($parameter['start_time']) {
                $where[] = ['c_entrust_time', '>=', $parameter['start_time']];
            }
            if ($parameter['end_time']) {
                $where[] = ['c_entrust_time', '<=', $parameter['end_time']];
            }
        }
        //最后跟进时间
        if ($request->input('date_type') == 2){
            if ($parameter['start_time']) {
                $where[] = ['c_followup_time', '>=', $parameter['start_time']];
            }
            if ($parameter['end_time']) {
                $where[] = ['c_followup_time', '<=', $parameter['end_time']];
            }
        }
        //首次录入时间
        if ($request->input('date_type') == 3){
            if ($parameter['start_time']) {
                $where[] = ['c_created_at', '>=', $parameter['start_time']];
            }
            if ($parameter['end_time']) {
                $where[] = ['c_created_at', '<=', $parameter['end_time']];
            }
        }
        //房屋类型
        if ($request->input('c_room_type')){
            $where[] = ['c_room_type', '=', $parameter['c_room_type']];
        }
        //房屋朝向
        if ($request->input('c_toward')){
            $where[] = ['c_toward', '=', $parameter['c_toward']];
        }
        //房屋价格 最小值
        if ($request->input('c_price_min')){
            $where[] = ['c_price_min', '>=', $parameter['c_price_min']];
        }
        //房屋价格 最大值
        if ($request->input('c_price_max')){
            $where[] = ['c_price_max', '<=', $parameter['c_price_max']];
        }
        //房屋面积 最小值
        if ($request->input('c_acreage_min')){
            $where[] = ['c_acreage_min', '>=', $parameter['c_acreage_min']];
        }
        //房屋面积 最大值
        if ($request->input('c_acreage_max')){
            $where[] = ['c_acreage_max', '<=', $parameter['c_acreage_max']];
        }
        //公私类型
        if ($request->input('c_customers_type')){
            $where[] = ['c_customers_type', '=', $parameter['c_customers_type']];
        }
        //门店ID
        if ($request->input('c_store_id')){
            $where[] = ['c_store_id', '=', $parameter['c_store_id']];
        }
        //员工ID
        if ($request->input('c_employees_id')){
            $where[] = ['c_employees_id', '=', $parameter['c_employees_id']];
        }
        //智能查询(keywords)   客户名字   客户手机号  地址
        $keywords = '';
        if ($request->input('keywords')){
            $keywords = trim($request->input('keywords'));
        }
        $list = $customers->listCustomers(env('PAGE_LIMIT_ADMIN'), $where, $keywords);
        if (!$list) {
            return $this->error(Error::NULL_DATA);
        }
        /**
         * 这里判断这个员工的ID   是不是老板  如果是的话   显示所有的客源列表信息
         * 如果不是的   客源的信息的详情不显示相应的内容
         */
        $data = $user->getUserType(Auth::user()->u_id);
        $type = $data['type'];
        $uId = $data['uid'];
        if ($type == 1){
            foreach($list as $k=>$v){
                if ($v->c_employees_id != $uId && $v->c_customers_type == 1){
                    $v->c_user_phone = '';
                }
            }
        }
        foreach ($list as $key=>$val) {
            $val->c_trading_type_name      = Type::getTypeDetail($val->c_trading_type);//交易类型
            $val->c_buy_status_name        = Type::getTypeDetail($val->c_buy_status);//购买状态
            $val->c_room_name              = Type::getTypeDetail($val->c_room);//房型
            $val->c_hall_name              = Type::getTypeDetail($val->c_hall);//厅
            $val->c_toilet_name            = Type::getTypeDetail($val->c_toilet);//卫
            $val->c_balcony_name           = Type::getTypeDetail($val->c_balcony);//阳台
            $val->c_source_type_name       = Type::getTypeDetail($val->c_source_type);//来源
            $val->c_entrust_type_name      = Type::getTypeDetail($val->c_entrust_type);//委托方式
            $val->c_user_level_name        = Type::getTypeDetail($val->c_user_level);//等级
            $val->c_live_type_name         = Type::getTypeDetail($val->c_live_type);//现住
            $val->c_professional_type_name = Type::getTypeDetail($val->c_professional_type);//类别
            $val->c_user_intention_name    = Type::getTypeDetail($val->c_user_intention);//意向
            $val->c_time_limit_name        = Type::getTypeDetail($val->c_time_limit);//期限
            $val->c_use_type_name          = Type::getTypeDetail($val->c_use_type);//用途
            $val->c_room_type_name         = Type::getTypeDetail($val->c_room_type);//房屋类型
            $val->c_toward_name            = Type::getTypeDetail($val->c_toward);//朝向
            $val->c_decorate_type_name     = Type::getTypeDetail($val->c_decorate_type);//装修
            $val->c_payment_type_name      = Type::getTypeDetail($val->c_payment_type);//付款
            //配套名字 c_complete
            $c_complete_name = array();//配套名字
            $completeArr = explode(',', $val->c_complete);
            foreach ($completeArr as $ke=>$va) {
                array_push($c_complete_name, Type::getTypeDetail($va));
            }
            $val->c_complete_name = implode(',', $c_complete_name);//配套的名字
            $val->c_pay_type_name      = Type::getTypeDetail($val->c_pay_type);//付佣
        }
        return $this->success('ok', $list);
    }

    /*
     * Wu Ning
     * 客源跟进
     */
    public function customerFollow(Request $request,Customers $customers)
    {
        $customersId = $request->input('cf_c_id');
        $list = $customers->customersFollow($customersId, env('PAGE_LIMIT_ADMIN'));
        if (!$list) {
           return $this->error(Error::NULL_DATA);
        }
        foreach ($list as $key=>$val) {
            $val->cf_fllow_type_name        = Type::getTypeDetail($val->cf_fllow_type);//跟进类型
        }
        return $this->success('ok', $list);
    }

    /*
     * 客源智能匹配推荐房源
     * Wu Ning
     */
    public function customersRecommendRoom(Request $request,Customers $customers)
    {
        $params = $request->all();
        //匹配房源
        $list = $customers->customersMatchingRoom($params);
        if ($list) {
            return $this->success('ok', $list);
        } else {
            return $this->success('ok', '没有匹配的房源');
        }
    }

    //添加、修改客源信息之前  查看该手机号的客源信息是否已经存在
    public function repeatAddition(Request $request,Customers $customers)
    {
        $c_user_phone = $request->input('c_user_phone');
        $c_id = $request->input('c_id');//修改有客源ID    添加没有客源ID
        if($c_id == null){
            $c_id = 0;
        }
        $cid = $customers->whether($c_user_phone, $c_id);
        if ($cid){
            $info = $this->getCustomersInfo($cid);
            return $this->success('ok', $info);
        }
        return $this->success('ok', '可以添加');
    }
    //查看录入 修改  有相同手机号客源的信息
    public function getCustomersInfo($cid)
    {
        $customers = new Customers();
        $list = $customers->customersSameList($cid);
        $user = new User();
        $data = $user->getUserType(Auth::user()->u_id);
        $type = $data['type'];
        $uId = $data['uid'];
        if ($type == 1){
            if ($list->c_employees_id != $uId && $list->c_customers_type == 1){
                $list->c_user_phone = '';
            }
        }
        return $list;
    }




    /**添加客源信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addCustomers(Request $request)
    {
        $params = $request->all();
        $validator = Validator::make($params, [
            'c_user_name'   => 'required',
            'c_user_phone'   => 'required',
            'c_trading_type'   => 'required',
            'c_buy_status'       => 'required',
            'c_area_id'   => 'required',
            'c_secondary_area'       => 'required',
            'c_room'   => 'required',
            'c_hall'   => 'required',
            'c_toilet'        => 'required',
            'c_acreage_max'   => 'required',
            'c_acreage_min'   => 'required',
            'c_price_max'   => 'required',
            'c_price_min'   => 'required',
            'c_entrust_time'   => 'required',
            'c_entrust_type'   => 'required',
            'c_user_level'   => 'required',
            'c_use_type'   => 'required',
            'c_floor'   => 'required'
           // 'cf_fllow_type' => 'required',//客源跟进方式
        ]);
        if ($validator->fails()) {
            return $this->error(Error::PARAM_MISSING);
        }
        //判断跟进字数太少不能录入
//        if (!$params['cf_content']) {
//            if (mb_strlen($params['cf_content'],'utf8') < 5) {
//                return $this->error(Error::CONTENT_LESS_THAN_FIVE);
//            }
//        }
        $customers = new Customers();
        $res = $customers->addCustomers($params);
        if (!$res) {
            return $this->error(Error::ADD_ERROR);
        }

        //匹配房源
        $list = $customers->customersMatchingRoom($params);
        if($list){
            return $this->success('ok', $list);
        }else{
            return $this->success('ok', '没有匹配的房源');
        }

    }

    /**修改客源信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updatecustomers(Request $request)
    {
        $params = $request->all();
        $validator = Validator::make($params, [
            'c_user_name'   => 'required',
            'c_user_phone'   => 'required',
            'c_trading_type'   => 'required',
            'c_buy_status'       => 'required',
            'c_area_id'   => 'required',
            'c_secondary_area'       => 'required',
            'c_room'   => 'required',
            'c_hall'   => 'required',
            'c_toilet'   => 'required',
            'c_acreage_max'   => 'required',
            'c_acreage_min'   => 'required',
            'c_price_max'   => 'required',
            'c_price_min'   => 'required',
            'c_entrust_time'   => 'required',
            'c_entrust_type'   => 'required',
            'c_user_level'   => 'required',
            'c_use_type'   => 'required',
            'c_floor'   => 'required',
            'c_id'   => 'required',
            'c_private_guest'   => 'required',

        ]);
        if ($validator->fails()) {
            return $this->error(Error::PARAM_MISSING);
        }
//        //判断跟进字数太少不能录入
//        if (mb_strlen($params['cf_content'],'utf8') < 5) {
//            return $this->error(Error::CONTENT_LESS_THAN_FIVE);
//        }
        $customers = new Customers();
        $status = $customers->updateCustomers($params);
        if (!$status) {
            return $this->error(Error::EDIT_ERROR);
        }
        //匹配房源
        $list = $customers->customersMatchingRoom($params);
        if($list){
            return $this->success('ok', $list);
        }else{
            return $this->success('ok', '没有匹配的房源');
        }

    }

    /**删除客源信息到回收站
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function recycleBin(Request $request)
    {
        $cId = $request->input('c_id');
        $customers = new Customers();
        $status = $customers->recyclebinCustomers($cId);
        if (!$status) {
            $this->error(Error::DEL_ERROR);
        }
        return $this->success('ok', '删除成功');
    }

    /**删除客源信息（硬删除）
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request)
    {
        $cId = $request->input('c_id');
        //dd($cId);
        $customers = new Customers();
        $status = $customers->delCustomers($cId);
        if (!$status) {
            $this->error(Error::DEL_ERROR);
        }
        return $this->success('ok', '删除成功');
    }

    /**
     * 回收站的客源信息
     */
    public function recycleBinInfo()
    {
        $customers = new Customers();
        $list = $customers->recycleBinList(env('PAGE_LIMIT_ADMIN'));
        if (!$list) {
            return $this->error(Error::NULL_DATA);
        }
        return $this->success('ok', $list);
    }


    /**
     * 客源结算业绩分配
     */
    public function addAchievement(Request $request,Customers $customers){

        $param = $request->all();
        $res = $customers->saveCustomersStatus($param);
        if($res['code'] == 1){
            return $this->success('ok', $res['msg']);
        }else{
            return $this->error(Error::ADD_ERROR);
        }
    }

    /**根据分类ID   获取该分类下面所有的种类 id以及 种类名称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAllTypeDetail(Request $request)
    {
        $params = $request->all();
        $vail = AdminVail::getType($params);
        if (!$vail) {
            return $this->error(Error::PARAM_MISSING);
        }
        //根据前端传过来的分类ID 来获取该分类下面的所有种类
        $list =Type::storageRedis($params['t_id']);
        if (!$list) {
            return $this->error(Error::NULL_DATA);
        }
        return $this->success('ok', $list);
    }

}